package wo.esys.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import wo.common.util.WoUtil;
import wo.esys.exception.ESysException;
import wo.esys.mapper.MenuMapper;
import wo.esys.mapper.UserMapper;
import wo.esys.po.Menu;
import wo.esys.po.Role;
import wo.esys.po.User;
import wo.esys.service.CoreService;
import wo.esys.util.ESysConstant;
import wo.esys.vo.WoUser;

@Transactional
@Service
public class CoreServiceImpl implements CoreService {

	@Resource
	private MenuMapper menuMapper;
	
	@Resource
	private UserMapper userMapper;
	
	@Override
	public List<Menu> findChildren(String parentId, WoUser u) {
		// 获取当前用户的角色，角色id为admin的角色是系统管理员
		List<Role> roles = userMapper.findRolesById(u.getId());
		// 保存当前用户是否管理员
		Boolean isAdmin = false;
		for (Role r : roles) {
			if ("admin".equals(r.getId())) {
				isAdmin = true;
			}
		}
		// 如果管理员，则返回所有子菜单
		if (isAdmin) {
			// 获取所有子菜单
			return menuMapper.findAllByParentId(parentId);
		}
		// 如果不是管理员，则还需要根据角色去过滤子菜单
		return menuMapper.findAllByParentIdAndRoles(parentId, roles);
	}

	@Override
	public WoUser authenticate(String user, String password) {
		if (WoUtil.isEmpty(user)) {
			throw new ESysException (ESysConstant.ERR_LOGIN_USER);
		}
		User u = userMapper.findByLoginName(user);
		if (u == null ) {
			throw new ESysException (ESysConstant.ERR_LOGIN_USER);
		}
		String passMd5 = WoUtil.getMD5(u.getId(), password);
		if (!passMd5.equals(u.getPassword())) {
			throw new ESysException (ESysConstant.ERR_LOGIN_USER);
		}
		return new WoUser(u);
	}

}
